package edu.uclmgmu.bacteriosec.domain;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class MainClassExecutor {
	private String classPath;
	private String mainClass;
	private String bootPath;
	private String aspectsJWeaverPath;
	private String workingPath;

	/**
	 * 
	 * @param currentPath Folder where the aspectJ class files are located
	 * @param classPath CLASSPATH required to execute the SUT
	 * @param mainClass	full name of the launching class 
	 * @param workingDirectory Folder where the mainClass is located
	 */
	public MainClassExecutor(String aspectsJWeaverPath, String classPath, String mainClass, String bootPath, String workingPath) {
		this.aspectsJWeaverPath=aspectsJWeaverPath;
		this.classPath=classPath;
		this.mainClass=mainClass;
		this.bootPath=bootPath;
		this.workingPath=workingPath;
	}

	public int executeProcess(String[] outputText) {
		List<String> comandos=new ArrayList<String>();
		comandos.add("java");
		if (this.bootPath!=null && this.bootPath.length()>0) {
			comandos.add("-Dsun.boot.class.path=" +  this.bootPath);
		}
		comandos.add("-javaagent:" + this.aspectsJWeaverPath);
		comandos.add("-cp");
		comandos.add(this.classPath);
		comandos.add(mainClass);
		
		if (outputText[0]==null)
			outputText[0]="";
		ProcessBuilder pb=new ProcessBuilder(comandos);
		File f=new File(this.workingPath);
		pb.directory(f);
		Map<String, String> env = pb.environment();
		env.put("CLASSPATH", this.classPath);
		try {
			pb.redirectErrorStream(true);
			Process p = pb.start();
			p.waitFor();
			BufferedReader brs = new BufferedReader(new InputStreamReader(p.getInputStream()));

			int car=0;
			while((car=brs.read())!=-1){
				try{
					outputText[0]+=((char) car)+brs.readLine();
				}catch(IllegalThreadStateException e){
					try {
						outputText[0]+=(brs.readLine());
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}
			}
			return p.exitValue();
		} catch (Exception e) {
			e.printStackTrace();
			return -1000;
		}
	}
	
	public void setBootPath(String bootPath) {
		this.bootPath = bootPath;
	}
}
